//
//  eeuiIdentifyAppModule.m
//  Pods
//

#import "eeuiIdentifyAppModule.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import <WeexPluginLoader/WeexPluginLoader.h>

@interface eeuiIdentifyAppModule ()

@end

@implementation eeuiIdentifyAppModule

@synthesize weexInstance;

WX_PlUGIN_EXPORT_MODULE(eeuiIdentify, eeuiIdentifyAppModule)
WX_EXPORT_METHOD_SYNC(@selector(check))
WX_EXPORT_METHOD(@selector(start:))

//检查是否支持生物认证
- (BOOL)check {
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error]) {
        return YES;
    } else {
        return NO;
    }
}

//开始生物认证
- (void)start:(WXModuleCallback)callback {
    if (callback == nil) {
        return;
    }
    if (![self check]) {
        callback(@{
                @"status": @"error",
                @"msg": @"不支持身份验证",
        });
        return;
    }
    LAContext *context = [[LAContext alloc] init];
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"验证身份" reply:^(BOOL success, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                callback(@{
                        @"status": @"success",
                        @"msg": @"验证成功",
                });
            } else {
                switch (error.code) {
                    case LAErrorUserCancel:
                        callback(@{
                                @"status": @"error",
                                @"msg": @"用户取消验证",
                        });
                        break;
                    case LAErrorPasscodeNotSet:
                        callback(@{
                                @"status": @"error",
                                @"msg": @"设配未设置密码",
                        });
                        break;

                    case LAErrorTouchIDNotAvailable:
                        callback(@{
                                @"status": @"error",
                                @"msg": @"设备未设置Touch ID",
                        });
                        break;

                    case LAErrorTouchIDNotEnrolled:
                        callback(@{
                                @"status": @"error",
                                @"msg": @"用户未录入指纹",
                        });
                        break;

                    default:
                        callback(@{
                                @"status": @"error",
                                @"msg": @"验证失败",
                        });
                        break;
                }
            }
        });
    }];
}

@end
